package api

import (
	__ "api_gateway/basic/proto"
	"api_gateway/pkg"
	"api_gateway/request"
	"context"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
	"time"
)

func Register(c *gin.Context) {

}

func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	log.Println(file.Filename)

	dst := "file/static/" + file.Filename

	// 上传文件至指定的完整文件路径
	err := c.SaveUploadedFile(file, file.Filename)
	if err != nil {
		return
	}

	if file.Size > 5*1024*1024 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "文件过大",
			"data": err.Error(),
		})
	}

	if dst != ".png" && dst != ".jpg" {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "文件只能是.png和.jpg",
			"data": err.Error(),
		})
	}

	pkg.Upload(file.Filename, dst)
	if dst != "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "上传成功",
			"data": "4301ccced3a081ff2ac4dde16c77258c.png",
		})
	}

}

func AddWorks(c *gin.Context) {
	var req request.AddWorks
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证",
			"data": err.Error(),
		})
		return
	}

	conn, err := grpc.NewClient("127.0.0.1:8888", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	s := __.NewUserClient(conn)

	// Contact the server and print out its response.
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	s.AddWorks(ctx, &__.AddWorksReq{
		Name:        req.Name,
		Describe:    req.Describe,
		Association: req.Association,
	})

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "上传成功",
		"data": true,
	})
}
